/*
 * lib.h
 *
 *  Created on: 2010.05.18
 *      Author: Tadas
 */

#ifndef LIB_H_
#define LIB_H_

#include <cmath>


#define EPS 1.0e-5
#define JMAX 20

using namespace std;

void brac_m(double (*fun)(double), double x1, double x2, int n, double xb1[], double xb2[], int &nb){
	int nbb, i;
	double x, fOld, fNew, dx;
	nbb = 0;
	dx = (x2 - x1)/n;
	fOld = fun(x = x1);
	for(i = 0; i < n; i++){
		fNew = fun(x += dx);
		if(fOld * fNew < 0.0){
			xb1[nbb] = x - dx;
			xb2[nbb] = x;
			nbb++;
			if(nbb == nb){
				return;
			}
		}
		fOld = fNew;
	}
	nb = nbb;
	return;
}

double bisec(double (*func)(double), double x1, double x2, int &ite){
	int j;
	double dx, f, fmid, xmid, rtb;
	f = func(x1);
	fmid = func(x2);
	
	if(f*fmid > 0){
		cout << "Naudojant Bisec saknis turi buti ireminta" << endl;
		return 0.0;
	}
	
	if( f < 0.0){
		rtb = x1;
		dx = x2 - x1;
	}
	else {
		rtb = x2;
		dx = x1 - x2;
	}
	
	for( j = 0; j < JMAX; j++){
		ite++;
		fmid  = func(xmid = rtb + (dx*=0.5));
		
		if(fmid <= 0.0)
			rtb = xmid;
		if(fabs(dx) < EPS || fmid == 0.0){
			return rtb;
		}
	}
	
	cout << "Per daug zingsniu" << endl;
	return 0.0;
}

double secant(double (*func)(double), double x1, double x2, int &ite){
	int j;
	float dx, fd, xd, swap, f, rtf;
	
	fd = func(x1);
	f = func(x2);
	
	if(fabs(fd) < fabs(f)){
		rtf = x1;
		xd = x2;
		swap = fd;
		fd = f;
		f = swap;
	}
	else {
		xd = x1;
		rtf = x2;
	}
	
	for(j = 0; j < JMAX; j++){
		ite++;
		dx = (xd - rtf)*f/(f-fd);
		xd = rtf;
		fd = f;
		
		rtf += dx;
		f = func(rtf);
		
		if(fabs(dx) < EPS || f == 0.0){
			return rtf;
		}
	}
	
	cout << "Per daug zingsniu secant funkcijoje" << endl;
	return 0.0;
	
}


double newtRaps(double (*fnc)(double), double (*fncd)(double), double x1, double x2, int &ite){
	int j;
	double dx, df, f, rtf;
	rtf = 0.5*(x1+x2);
	
	for(j = 0; j < JMAX; j++){
		ite++;
		dx = fnc(rtf)/fncd(rtf);
		rtf -= dx;
		
		if( (x1-rtf)*(rtf-x2) < 0.0){
			cout << "Taskas issoko uz pradiniu reziu" << endl;
			return rtf;
		}
		if(fabs(dx) < EPS){
			return rtf;
		}
	}
	
	cout << "Per daug iteraciju newtRaps" << endl;
	return 0.0;
}

#endif /* LIB_H_ */
